import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';
import {SecurityService} from "../service/auth.service";

@Directive({
    selector: '[hasProjectPermission]'
})
export class HasProjectPermissionDirective {
    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef,
        private securityService: SecurityService
    ) {
    }

    @Input()
    set hasProjectPermission(params: string[]) {
        try {
            const projectId = params[0];
            const permission = params[1];
            this.securityService.getUser()?.subscribe(rs => {
                if (rs.status === 'OK') {
                    if (rs.content === 'admin') {
                        this.viewContainer.clear();
                        this.viewContainer.createEmbeddedView(this.templateRef);
                        return
                    } else {
                        this.viewContainer.clear();
                        this.securityService.loadUserProjectPermissions(projectId).subscribe((rs: any) => {
                            if (rs.status === 'OK') {
                                if (rs.content.indexOf(permission) == -1) {
                                    this.viewContainer.clear();
                                } else {
                                    this.viewContainer.createEmbeddedView(this.templateRef);
                                }
                            }
                        })
                    }
                }
            })

        } catch (e) {
            console.error(`权限判断错误，默认隐藏：${e}`);
            this.viewContainer.createEmbeddedView(this.templateRef);
        }
    }

}